package com.example.hanchen.yongkanggy.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.hanchen.yongkanggy.BR;
import com.example.hanchen.yongkanggy.R;
import com.example.hanchen.yongkanggy.databinding.ActivityFeedbackBinding;
import com.example.hanchen.yongkanggy.databinding.ActivitySettingBinding;
import com.example.hanchen.yongkanggy.entity.ImageAddEntity;
import com.example.hanchen.yongkanggy.entity.ImageEntity;
import com.example.hanchen.yongkanggy.entity.StatusCode;
import com.example.hanchen.yongkanggy.entity.verificationimgEntity;
import com.example.hanchen.yongkanggy.home.adapter.AddImageAdapter;
import com.example.hanchen.yongkanggy.home.base.StatusBarDatabindingActivity;
import com.example.hanchen.yongkanggy.home.viewmodel.HomeViewModel;
import com.example.hanchen.yongkanggy.http.ConstantData;
import com.example.hanchen.yongkanggy.http.FileUploadTask;
import com.example.hanchen.yongkanggy.http.ImageUploadTask;
import com.example.hanchen.yongkanggy.http.ObsTask;
import com.example.hanchen.yongkanggy.http.PostFile;
import com.example.hanchen.yongkanggy.http.UserViewModel;
import com.example.hanchen.yongkanggy.utils.AesUtils;
import com.example.hanchen.yongkanggy.utils.DialogUtils;
import com.example.hanchen.yongkanggy.utils.Md5Utils;
import com.example.hanchen.yongkanggy.utils.Page;
import com.example.hanchen.yongkanggy.utils.PreferencesUtil;
import com.example.hanchen.yongkanggy.utils.SharePreferencesConsts;
import com.example.hanchen.yongkanggy.utils.ToolsUtils;
import com.example.hanchen.yongkanggy.utils.TreeMapUtils;
import com.example.hanchen.yongkanggy.utils.UriToPathUtil;
import com.google.gson.Gson;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/*
 * 意见反馈主界面
 * */
public class FeedbackActivity extends StatusBarDatabindingActivity<ActivityFeedbackBinding, HomeViewModel> {

    AddImageAdapter addImageAdapter;
    List<ImageAddEntity> imageAddEntityList = new ArrayList<>();

    private Dialog headDialog;

    private File tempFile;
    // 创建用于保存照片的文件
    File photoFile = null;

//    ObsTask obsTask;

    Handler mainHandler = new Handler(Looper.getMainLooper());

    PostFile postFile;

    private UserViewModel userViewModel;
    private static final int REQUEST_CODE_PICK_IMAGE = 1001;

    @Override
    protected int initLayoutID(Bundle savedInstanceState) {
        return R.layout.activity_feedback;
    }

    @Override
    public int initVariableId() {
        return BR.Feedbackmodel;
    }

    @Override
    protected void initView() {
//        obsTask = new ObsTask(FeedbackActivity.this);
        tempFile = new File(ToolsUtils.getTimestamp() + "wyt/image");
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        postFile = new PostFile();

        mDatabinding.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ImageAddEntity imageAddEntity = new ImageAddEntity();
        imageAddEntity.setId(imageAddEntityList.size() + 1);
        imageAddEntity.setState(1);
        imageAddEntity.setImage("");

        imageAddEntityList.add(imageAddEntity);

        addImageAdapter = new AddImageAdapter(this, new AddImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                requestPermission();
            }

            @Override
            public void onItemClick2(int position) {/*删除图片*/
                imageAddEntityList.remove(position);
                addImageAdapter.setTabData(imageAddEntityList);
            }
        });

        mDatabinding.rvEvaluate.setLayoutManager(new GridLayoutManager(this, 3));
        mDatabinding.rvEvaluate.setAdapter(addImageAdapter);
        addImageAdapter.setTabData(imageAddEntityList);
    }

    @Override
    protected void initData() {

        mDatabinding.etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 200) {
                    // 如果用户输入的字符数超过200，你可以在这里处理
                    // 比如截断文本，显示提示信息等
                    Toast.makeText(FeedbackActivity.this, "最多只能输入200字", Toast.LENGTH_SHORT).show();
                } else {
                    mDatabinding.tvNumber.setText(editable.length() + "/" + 200);
                }
            }
        });

        mDatabinding.tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(FeedbackActivity.this, FeedbackItemActivity.class));
                finish();
            }
        });
    }


    private void verificationimg(File file, String moduleName) {
        LiveData<verificationimgEntity> userLiveData = userViewModel.verificationimg(file, moduleName);
        userLiveData.observe(FeedbackActivity.this, user -> {
            Log.i("JFOEJFIJE", "SDJFLDJJF  " + user.getCode() + "   " + user.getMsg());
            try {
                Toast.makeText(FeedbackActivity.this, user.getData(), Toast.LENGTH_SHORT).show();
                if (user.getCode() == 200) {
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    /*相机和相册*/
    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermission() {
        PackageManager pm = getPackageManager();
        boolean permission_readStorage = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.READ_EXTERNAL_STORAGE", FeedbackActivity.this.getPackageName()));
        boolean permission_writeStorage = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", FeedbackActivity.this.getPackageName()));
        boolean permission_camera = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.CAMERA", FeedbackActivity.this.getPackageName()));

        // 第一次请求权限时，用户如果拒绝，下一次请求shouldShowRequestPermissionRationale()返回true
        // 向用户解释为什么需要这个权限
        if (!(permission_camera && permission_writeStorage && permission_readStorage)) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
            }, 1);
        } else {
            if (headDialog == null) {
                View view = LayoutInflater.from(this).inflate(R.layout.activity_select_head, null);
                headDialog = DialogUtils.initDialog(this, view, R.style.MyDialogBottomInOutTheme, true, Gravity.BOTTOM);
                Button takePhoto = view.findViewById(R.id.take_photo);
                Button selectPhoto = view.findViewById(R.id.select_photo);
                Button btnCancel = view.findViewById(R.id.btn_cancel);
                takePhoto.setOnClickListener(view1 -> {/*相机*/
                    headDialog.dismiss();
                    dispatchTakePictureIntent();

                });
                selectPhoto.setOnClickListener(view1 -> {/*相册*/
                    headDialog.dismiss();
                    openGallery(tempFile);
                });
                btnCancel.setOnClickListener(view1 -> {
                    headDialog.dismiss();
                });
            }
            headDialog.show();
        }
    }

    /*相机拍摄*/
    public void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // 错误处理
            }
            // 如果文件创建成功，则继续
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(
                        this,
                        "com.example.hanchen.yongkanggy.fileProvider",
                        photoFile
                );
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, Page.OPEN_GALLERY_CODE);
            }
        }
    }

    /**
     * 打开相册
     */
    public void openGallery(File tempFile) {
//        Intent intent = new Intent(Intent.ACTION_PICK);// 打开相册
//        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
//        intent.putExtra("output", Uri.fromFile(tempFile));
//        startActivityForResult(intent, Page.PHOTO_ALBUM);


        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
//        startActivity(intent);

//        File imageFileFromGallery = getImageFileFromGallery(this, intent);
//        sendPostWithOkHttp(url, imageFileFromGallery);
    }


    public File getImageFileFromGallery(Context context, Intent data) {
        Uri selectedImageUri = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = context.getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        File imageFile = new File(picturePath);
        return imageFile;
    }


    public File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        String absolutePath = image.getAbsolutePath();
        return image;
    }

    //    String url="http://ykga.java.68hanchen.com/verification/img";
    String url = "http://ykga.java.68hanchen.com/api-client/verification/img";

    @SuppressLint("NewApi")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case Page.OPEN_GALLERY_CODE:/*相机*/
                if (photoFile != null) {
                    // 使用photoFile来访问拍摄的照片
                    // 例如，你可以使用BitmapFactory.decodeFile(photoFile.getAbsolutePath())来加载为Bitmap
//                    String pathFromUri = UriToPathUtil.getPathFromUri(FeedbackActivity.this, Uri.parse(photoFile.getAbsolutePath()));
//                    Log.i("上传路径返回值打印--拍照：", pathFromUri);
//                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//                    String imageFileName = "wyt_" + timeStamp;

                    String absolutePath = photoFile.getAbsolutePath();
                    File file = new File(absolutePath);
                    Log.i("上传路径返回值打印--拍照：", absolutePath);
                    sendPostWithOkHttp(url, file);

//                    new  Upload(file).execute(url);


//                    verificationimg(file,"qwe");


//                    postFile.postFiles("http://ykga.java.68hanchen.com/verification/img",file);
//                    postFile.postFileAndModuleName("http://ykga.java.68hanchen.com/verification/img",file,"moduleName");
//                    try {

//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }


//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//
//
//
//
//                            new Thread(new FileUploadTask(pathFromUri, "http://192.168.0.2:8009/verification/img")).start();
//
//
////                            // 使用示例
////                            ImageUploadTask.UploadCallback callback = new ImageUploadTask.UploadCallback() {
////                                @Override
////                                public void onSuccess(String response) {
////                                    // 处理成功响应
////                                    Log.i("JFOEIFJEIFDDDDD", "上传成功");
////
////                                }
////
////                                @Override
////                                public void onFailure(String error) {
////                                    // 处理失败信息
////                                    Log.i("JFOEIFJEIFDDDDD", "上传失败");
////                                }
////                            };
////                            new Thread(new ImageUploadTask(pathFromUri,"Question Feedback", "http://ykga.java.68hanchen.com/verification/img",callback)).start();
////
//////
////                            Callback callback = new Callback() {
////                                @Override
////                                public void onResponse(Call call, Response response) throws IOException {
////                                    if (response.isSuccessful()) {
////                                        String path = response.body().string();
////                                        // 使用Glide或Picasso加载图片
//////                                        Glide.with(context).load(path).into(imageView);
////                                        Log.i("JFOEIFJEIFDDDDD", path);
////                                    }
////                                }
////
////                                @Override
////                                public void onFailure(Call call, IOException e) {
////                                    // 处理错误
////                                }
////                            };
////                            File imageFile = new File(pathFromUri);
////                            FileUploadTask.uploadImage(imageFile, callback);
//
//
//                            String imagePath = obsTask.putObject("wyt/imageAdapter/" + imageFileName, pathFromUri);
////                            Log.i("JFOEIFJEIFDDDDD", imagePath);
////                            if (TextUtils.isEmpty(imagePath)) {
////                                Toast.makeText(FeedbackActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
////                                return;
////                            }
////                            ImageAddEntity imageAddEntity = new ImageAddEntity();
////                            imageAddEntity.setId(imageAddEntityList.size() + 1);
////                            imageAddEntity.setState(2);
////                            imageAddEntity.setImage(imagePath);
////                            imageAddEntityList.add(imageAddEntity);
////                            Log.i("JIFJIEFJIEFEFa", "   " + imageAddEntityList.size());
////                            imageAddEntityList.sort((o1, o2) -> o2.getId() - o1.getId()); // 逆序排序
////////
////                            mainHandler.post(new Runnable() {
////                                @Override
////                                public void run() {
////                                    // 在主线程中更新UI
////                                    addImageAdapter.setTabData(imageAddEntityList);
////                                }
////                            });
//                        }
//                    }).start();
                }

                break;
            case REQUEST_CODE_PICK_IMAGE:/*相册*/
                Uri imageUri = data.getData();

                File fileFromUri = UriToPathUtil.getFileFromUri(FeedbackActivity.this, imageUri);
                Log.i("上传路径返回值打印--相册：", fileFromUri+"    "+data.getData());
                sendPostWithOkHttp(url, fileFromUri);

//                try {



//                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//                    String imageFileName = "wyt_" + timeStamp;
//                    String absolutePath = photoFile.getAbsolutePath();

//                    File file = new File(fileFromUri);



//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            String imagePath = obsTask.putObject("wyt/imageAdapter/" + imageFileName, pathFromUri2);
//
//                            ImageAddEntity imageAddEntity = new ImageAddEntity();
//                            imageAddEntity.setId(imageAddEntityList.size() + 1);
//                            imageAddEntity.setState(2);
//                            imageAddEntity.setImage(imagePath);
//                            imageAddEntityList.add(imageAddEntity);
//                            imageAddEntityList.sort((o1, o2) -> o2.getId() - o1.getId()); // 逆序排序
//
//                            mainHandler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    // 在主线程中更新UI
//                                    addImageAdapter.setTabData(imageAddEntityList);
//                                }
//                            });
//                        }
//                    }).start();

//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                break;
            default:
                break;
        }
    }



    public String sendPostWithOkHttp(String url, File tempFile) {
        Log.i("JFOEIJIOE", "url " + url + "  file  " + tempFile);

        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), tempFile);
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", tempFile.getName(), requestBody)
                .addFormDataPart("moduleName", "footerImg")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
                Log.i("JFOEIFJEIFDDDDD", "失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                if (response.isSuccessful()) {
//                Log.i("JFOEIFJEIFDDDDD", "成功" + "  " + response.body().string());
                String responseStr = response.body().string();
                filemanager(responseStr);
                // 处理响应
//                }
            }
        });
        return url;
    }

    private void filemanager(String data) {
        Gson gson = new Gson();
        ImageEntity imageEntity = gson.fromJson(data, ImageEntity.class);
        if (imageEntity.getCode() == 200) {

            ImageAddEntity imageAddEntity = new ImageAddEntity();
            imageAddEntity.setId(imageAddEntityList.size() + 1);
            imageAddEntity.setState(2);
            imageAddEntity.setImage(imageEntity.getData());
            imageAddEntityList.add(imageAddEntity);
            Log.i("JIFJIEFJIEFEFa", "   " + imageEntity.getData());
            imageAddEntityList.sort((o1, o2) -> o2.getId() - o1.getId()); // 逆序排序
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 在主线程中更新UI
                    addImageAdapter.setTabData(imageAddEntityList);
                }
            });

        }
        /*清除缓存*/
//        webView.clearCache(true);
    }
}